package pub.cleangao.mqtt.processor;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProcessorFactory implements ApplicationRunner {

    @Autowired
    private ApplicationContext applicationContext;

    // key:topic, value:processor
    private static final Map<String, Processor> topicProcessorMap = new HashMap<>();


    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<String, Processor> beanMap = applicationContext.getBeansOfType(Processor.class);
        if (beanMap == null || beanMap.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Processor> entry : beanMap.entrySet()) {
            Processor processor = entry.getValue();
            if (processor == null) {
                continue;
            }
            topicProcessorMap.put(processor.topic(), processor);
        }
    }


    public static Processor getProcessor(String topic) {
        return topicProcessorMap.get(topic);
    }
}
